package com.nbcio.modules.estar.bs.service.impl;

import com.nbcio.modules.estar.bs.bean.KeyValue;
import com.nbcio.modules.estar.bs.cache.CacheHelper;
import com.nbcio.modules.estar.bs.constant.BsConstant;
import com.nbcio.modules.estar.bs.constant.Enabled;
import com.nbcio.modules.estar.bs.constant.EstarKeyConstant;
import com.nbcio.modules.estar.bs.entity.BsDict;
import com.nbcio.modules.estar.bs.entity.BsDictItem;
import com.nbcio.modules.estar.bs.mapper.BsDictItemMapper;
import com.nbcio.modules.estar.bs.mapper.BsDictMapper;
import com.nbcio.modules.estar.bs.service.IBsDictService;
import com.nbcio.modules.estar.bs.util.EstarUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: bs_dict
 * @Author: nbacheng
 * @Date:   2024-08-21
 * @Version: V1.0
 */
@Service
public class BsDictServiceImpl extends ServiceImpl<BsDictMapper, BsDict> implements IBsDictService {

	@Autowired
    private BsDictMapper bsDictMapper;

    @Autowired
    private BsDictItemMapper bsDictItemMapper;

    @Autowired
    private CacheHelper cacheHelper;
	/**
     * 根据国际化语言查询指定字典编码下拉列表
     * 先从Redis中获取
     * @param dictCode 字典名称
     * @param language 语言
     * @return
     */
	@Override
	public List<KeyValue> select(String dictCode, String language) {
		
		//缓存字典Key
        String dictKey = EstarKeyConstant.DICT_PREFIX  + language + BsConstant.REDIS_SPLIT + dictCode;

        Map<String, String> dictMap = cacheHelper.hashGet(dictKey);

        //当查询的字典为空时
        if (CollectionUtils.isEmpty(dictMap)) {
            LambdaQueryWrapper<BsDictItem> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(BsDictItem::getDictCode, dictCode)
                    .eq(BsDictItem::getEnabled, Enabled.YES.getValue())
                    .eq(BsDictItem::getLocale, language)
                    .orderByAsc(BsDictItem::getSort);

            List<BsDictItem> list = bsDictItemMapper.selectList(wrapper);

            List<KeyValue> keyValues = list.stream()
                    .map(dictItemEntity -> new KeyValue(dictItemEntity.getItemValue(), dictItemEntity.getItemName(), dictItemEntity.getItemExtend()))
                    .collect(Collectors.toList());
            //当缓存不存在时，刷新缓存
            List<String> dictCodes = new ArrayList<>();
            dictCodes.add(dictCode);
            refreshCache(dictCodes);
            return keyValues;
        }

        List<KeyValue> keyValues = EstarUtils.formatKeyValue(dictMap);

        //添加扩展字段
        LambdaQueryWrapper<BsDictItem> bsDictItemWrapper = Wrappers.lambdaQuery();
        bsDictItemWrapper.eq(BsDictItem::getDictCode, dictCode);
        bsDictItemWrapper.isNotNull(BsDictItem::getItemExtend);

        Map<String, String> extendMap = bsDictItemMapper.selectList(bsDictItemWrapper).stream()
                .filter(gaeaDictItem -> StringUtils.isNotBlank(gaeaDictItem.getItemExtend()))
                .collect(Collectors.toMap(BsDictItem::getItemValue, BsDictItem::getItemExtend, (v1, v2) -> v2));
        if (!CollectionUtils.isEmpty(extendMap)) {
            keyValues.stream().forEach(keyValue -> keyValue.setExtend(extendMap.get(keyValue.getId())));
        }
        return keyValues;
	}
	/**
     * 刷新全部缓存
     * @param dictCodes
     */
    @Override
    public void refreshCache(List<String> dictCodes) {

        //查询指定字典项
        List<BsDictItem> bsDictItems = findItems(dictCodes);

        //对数据字典项进行分组，分组key=语言标识:字典编码
        Map<String, Map<String, String>> dictItemMap = bsDictItems.stream()
                .collect(Collectors
                        .groupingBy(item -> item.getLocale() + BsConstant.REDIS_SPLIT +item.getDictCode(),
                                Collectors.toMap(BsDictItem::getItemValue, BsDictItem::getItemName,(v1,v2)-> v2)));

        //遍历并保持到Redis中
        dictItemMap.entrySet().stream().forEach(entry -> {
            String key = EstarKeyConstant.DICT_PREFIX  + entry.getKey();
            cacheHelper.delete(key);
            cacheHelper.hashSet(key, entry.getValue());
        });
    }
    @Override
    public List<BsDictItem> findItems(List<String> dictCodes) {

        LambdaQueryWrapper<BsDictItem> gaeaDictItemQueryWrapper = Wrappers.lambdaQuery();
        gaeaDictItemQueryWrapper.eq(BsDictItem::getEnabled, Enabled.YES.getValue());
        if (!CollectionUtils.isEmpty(dictCodes)) {
            gaeaDictItemQueryWrapper.in(BsDictItem::getDictCode, dictCodes);
        }
        return bsDictItemMapper.selectList(gaeaDictItemQueryWrapper);
    }

}
